package study.io.springboot.upload.service;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import study.io.springboot.upload.support.utils.CopyUtils;
import study.io.springboot.upload.support.utils.URLUtils;

import java.net.URL;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AsyncCopyService {

    public void copy(List<String> urlLt, String dest) {
        List<URL> myUrlLt = URLUtils.toURLs(urlLt);
        List<CompletableFuture> resultLt = myUrlLt.stream()
                .map(url -> copy(url, dest))
                .collect(Collectors.toList());

        CompletableFuture<Void> done = CompletableFuture.allOf(resultLt.toArray(new CompletableFuture[resultLt.size()]));
    }

    private CompletableFuture<Void> copy(URL url, String desc) {
        return CompletableFuture.runAsync(() -> {
            Stopwatch stopwatch = Stopwatch.createStarted();
            CopyUtils.copyURLToFile(url, desc);
            log.info(">>>>>>>>>> {} sec", stopwatch.elapsed(TimeUnit.SECONDS));
        });
    }
}
